const router = require('koa-router')()
const fs=require('fs')
const path=require('path')

router.get('/', async (ctx, next) => {
  await ctx.render('index', {
    title: 'Hello Koa 2!'
  })
})

router.post('/upload',async (ctx,next)=>{
  // 通过ctx.request.files获取文件，后面的file是上传时name值
  //上传多个文件
  const files=ctx.request.files.file;
  console.log('hhh')
  console.log(files)
  for(let file of files){
    // 创建可读流
    const reader=fs.createReadStream(file.path)
    // 获取上传文件扩展名
    // path.resolve(__dirname,'..')返回上一级目录
    let filePath=path.join(path.resolve(__dirname,'..'),`public/upload/${file.name}`)
    console.log('filePath:'+filePath)
    // 创建可写流
    const upStream=fs.createWriteStream(filePath)
    reader.pipe(upStream)
  }
  return ctx.body='上传成功'
})

router.get('/string', async (ctx, next) => {
  ctx.body = 'koa2 string'
})

router.get('/json', async (ctx, next) => {
  ctx.body = {
    title: 'koa2 json'
  }
})

module.exports = router
